<script setup lang="ts">
import { HomeWrap } from '@/components/HomeWrap'
import { ref, onMounted, onUnmounted } from 'vue'
import ProductCard from './components/ProductCard.vue'
import ImgCarousel from './components/ImgCarousel.vue'
import { getPageList } from '@/api/product/client'
import type { ProductItem } from '@/api/product/types'

defineOptions({
  name: 'Home'
})

// 商品数据相关
const productList = ref<ProductItem[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const hasMore = ref(true)

// 获取商品列表
const fetchProductList = async () => {
  if (loading.value || !hasMore.value) return

  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }

    const res = await getPageList(params)
    if (res && res.data.list) {
      // 如果是第一页，清空原有数据
      if (currentPage.value === 1) {
        productList.value = res.data.list
      } else {
        // 否则追加数据
        productList.value = [...productList.value, ...res.data.list]
      }

      total.value = res.data.total
      // 修正 hasMore 判断逻辑：当前页码小于总页数时还有更多数据
      hasMore.value = currentPage.value < res.data.totalPage

      // 如果还有更多数据，准备加载下一页
      if (hasMore.value) {
        currentPage.value++
      }
      console.log('hasMore:', hasMore.value)
      console.log('total:', currentPage.value)
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 监控页面滚动
const handlePageScroll = () => {
  const mainWrap = document.querySelector('.main-wrap')
  if (!mainWrap) return

  const scrollTop = mainWrap.scrollTop
  const clientHeight = mainWrap.clientHeight
  const scrollHeight = mainWrap.scrollHeight
  // 当滚动到底部附近时加载更多
  if (scrollTop + clientHeight >= scrollHeight - 100) {
    console.log('滚动到底部，触发加载更多数据')
    fetchProductList()
  }
}

// 组件挂载时初始化
onMounted(() => {
  fetchProductList()
  // 监听 main-wrap 的滚动事件
  const mainWrap = document.querySelector('.main-wrap')
  console.log('mainWrap:', mainWrap)
  if (mainWrap) {
    mainWrap.addEventListener('scroll', handlePageScroll)
  }
})

// 组件销毁前清理事件监听
onUnmounted(() => {
  const mainWrap = document.querySelector('.main-wrap')
  if (mainWrap) {
    mainWrap.removeEventListener('scroll', handlePageScroll)
  }
})
</script>

<template>
  <HomeWrap>
    <!-- 图片轮播 -->
    <ImgCarousel />

    <!-- 商品列表 -->
    <div class="goods-wrap">
      <ProductCard v-for="product in productList" :key="product.skuId" :product="product" />

      <!-- 加载提示 -->
      <div v-if="loading" class="loading-tip"> 加载中... </div>

      <!-- 无更多数据提示 -->
      <div v-else-if="!hasMore && productList.length > 0" class="no-more-tip"> 没有更多商品了 </div>
    </div>
  </HomeWrap>
</template>

<style scoped>
.goods-wrap {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  grid-auto-rows: min-content;
  gap: 16px;
  justify-content: center;
  padding: 16px;
  max-width: 1200px;
  margin: 0 auto;
  /* 移除固定高度，让内容自然展开 */
  min-height: calc(100vh - 300px);
}

.loading-tip,
.no-more-tip {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}

@media (min-width: 768px) {
  .goods-wrap {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 20px;
    padding: 20px;
  }
}

@media (min-width: 1024px) {
  .goods-wrap {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 24px;
    padding: 24px;
  }
}
</style>
